package com.markerhub.controller;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.markerhub.common.dto.LoginDto;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.User;
import com.markerhub.service.UserService;
import com.markerhub.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
@Slf4j
@RestController
public class AccountController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 用户名密码登录会很麻烦，会有同用户名密码的情况
     * 最好用手机号或者邮箱登录
     * @param loginDto
     * @param response
     * @return
     */
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){
        //查询数据库 判断密码(数据库中密码要用md5加密)
        User dbUser = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        if(dbUser==null){
            return Result.fail("用户不存在");
        }
        if(!dbUser.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.fail("密码错误");
        }
        String token= jwtUtils.generateToken(dbUser.getId());
        //生成的token返回前端
        response.setHeader("Authorization",token);
        //很重要，跨域前端要接收返回的response的token需要这一行代码Access-Control-Expose-Headers不能写错
        response.setHeader("Access-Control-Expose-Headers","Authorization");


        return Result.success(MapUtil.builder()
                .put("id",dbUser.getId())
                .put("username",dbUser.getUsername())
                .put("avatar",dbUser.getAvatar())
                .put("email",dbUser.getEmail())
                .map());
    }

    /**
     * 需要登录后才能调用
     * @return
     */
    @RequiresAuthentication
    @PostMapping("/logout")
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }

}
